/**
 * 简化的安全更新工具
 * 避免复杂的视图更新问题
 */

/**
 * 简单安全更新
 * @param {Object} component - Vue组件实例
 * @param {Object} data - 要更新的数据
 * @returns {Promise}
 */
export function simpleUpdate(component, data) {
  return new Promise((resolve, reject) => {
    if (!component || component._isDestroyed || component._isBeingDestroyed || component._isComponentActive === false) {
      console.warn('组件已销毁或不活跃，跳过更新')
      resolve()
      return
    }

    try {
      // 验证数据
      if (!data || typeof data !== 'object' || Object.keys(data).length === 0) {
        console.warn('无效的更新数据:', data)
        resolve()
        return
      }

      // 使用 nextTick 确保在合适的时机更新
      component.$nextTick(() => {
        try {
          if (!component._isDestroyed && !component._isBeingDestroyed && component._isComponentActive !== false) {
            Object.keys(data).forEach(key => {
              if (data[key] !== undefined) {
                // 安全赋值，避免响应式系统错误
                try {
                  component[key] = data[key]
                } catch (assignError) {
                  console.warn(`赋值失败 ${key}:`, assignError)
                }
              }
            })
          }
          resolve()
        } catch (nextTickError) {
          console.error('nextTick 内更新失败:', nextTickError)
          reject(nextTickError)
        }
      })
    } catch (error) {
      console.error('更新失败:', error)
      reject(error)
    }
  })
}

/**
 * 批量更新
 * @param {Object} component - Vue组件实例
 * @param {Array} updates - 更新数组
 */
export async function batchUpdate(component, updates) {
  for (const update of updates) {
    await simpleUpdate(component, update)
  }
}

export default {
  simpleUpdate,
  batchUpdate
}